import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'dart:async';
import '../../../common/utils/index.dart';
import '../../../common/models/video/index.dart';

class HomeIndexController extends GetxController with GetSingleTickerProviderStateMixin {
  HomeIndexController();
  
  static const String tag = 'HomeIndexController';

  PageController? _pageController;
  
  // PageController的getter
  PageController get pageController {
    _pageController ??= PageController();
    return _pageController!;
  }
  
  // 当前页面索引
  RxInt currentPageIndex = 0.obs;
  
  // 视频列表
  RxList<VideoItem> videoList = <VideoItem>[].obs;
  
  // 当前播放的视频索引
  RxInt currentPlayingIndex = 0.obs;
  
  // 当前顶部Tab索引 (0-推荐, 1-热播, 2-关注, 3-商城)
  RxInt currentTopTabIndex = 0.obs;
  
  // ==================== 生命周期管理相关 ====================
  
  // 视频播放状态管理
  RxBool isVideoPlaying = true.obs;        // 视频是否正在播放
  RxBool isPageVisible = true.obs;         // 页面是否可见
  bool _wasPlayingBeforeBackground = true; // 进入后台前是否在播放
  
  // 生命周期管理器
  AppLifecycleManager? _lifecycleManager;
  
  // 路由观察者
  bool _isRouteObserverRegistered = false;
  Timer? _routeObserverTimer;
  
  // 头像列表
  final List<String> _avatarUrls = [
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_1.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_2.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_3.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_4.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_5.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_6.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_7.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_8.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_9.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_10.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_11.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_12.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_13.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_14.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_15.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_17.webp',
    'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_18.webp',
  ];

  _initData() {
    // 加载视频数据
    _loadVideoData();
    
    update(["home_index"]);
  }
  
  // 获取随机头像
  String _getRandomAvatar() {
    return _avatarUrls[Random().nextInt(_avatarUrls.length)];
  }

  // 加载视频数据
  void _loadVideoData() {
    // 视频数据列表（对应 douyin_videos.md）
    final List<Map<String, dynamic>> videoData = [
      {
        'id': '01d434a9f891da200c0d536cc06226b2',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/01d434a9f891da200c0d536cc06226b2.mp4',
        'coverImage': 'assets/images/01d434a9f891da200c0d536cc06226b2.jpg',
        'author': '@小姐姐',
        'avatarUrl': _getRandomAvatar(),
        'title': '分享日常美好瞬间',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '04a932934565bc5c1df9f77c02a9af24',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/04a932934565bc5c1df9f77c02a9af24.mp4',
        'coverImage': 'assets/images/04a932934565bc5c1df9f77c02a9af24.jpg',
        'author': '@时尚达人',
        'avatarUrl': _getRandomAvatar(),
        'title': '今日穿搭分享',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '197b0a4fa0c4eebcf468a02e6c1c7664',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/197b0a4fa0c4eebcf468a02e6c1c7664.mp4',
        'coverImage': 'assets/images/197b0a4fa0c4eebcf468a02e6c1c7664.jpg',
        'author': '@生活记录',
        'avatarUrl': _getRandomAvatar(),
        'title': '记录生活的美好',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '1ee8ddbffa5526b49e211ea3a3da9a2f',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/1ee8ddbffa5526b49e211ea3a3da9a2f.mp4',
        'coverImage': 'assets/images/01d434a9f891da200c0d536cc06226b2.jpg', // 使用备用图片
        'author': '@精彩瞬间',
        'avatarUrl': _getRandomAvatar(),
        'title': '捕捉美好时刻',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '2846ea33b65f2ac7890d421f3b1cd708',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/2846ea33b65f2ac7890d421f3b1cd708.mp4',
        'coverImage': 'assets/images/2846ea33b65f2ac7890d421f3b1cd708.jpg',
        'author': '@创意生活',
        'avatarUrl': _getRandomAvatar(),
        'title': '分享有趣创意',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '328e3d355dee43d28a5e6c8d9a03736f',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/328e3d355dee43d28a5e6c8d9a03736f.mp4',
        'coverImage': 'assets/images/328e3d355dee43d28a5e6c8d9a03736f.jpg',
        'author': '@萌宠日常',
        'avatarUrl': _getRandomAvatar(),
        'title': '可爱萌宠时刻',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '4690e3b4b1ced0e6e7d8e54e279b2da7',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/4690e3b4b1ced0e6e7d8e54e279b2da7.mp4',
        'coverImage': 'assets/images/4690e3b4b1ced0e6e7d8e54e279b2da7.jpg',
        'author': '@美食探店',
        'avatarUrl': _getRandomAvatar(),
        'title': '探索美味',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': '63f240cac36dc445fa2006f7f4271ef6',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/63f240cac36dc445fa2006f7f4271ef6.mp4',
        'coverImage': 'assets/images/63f240cac36dc445fa2006f7f4271ef6.jpg',
        'author': '@旅行日记',
        'avatarUrl': _getRandomAvatar(),
        'title': '世界那么大',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
      {
        'id': 'a45745c1d62743a83a2448b9055c829a',
        'videoUrl': 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/dy_videos/a45745c1d62743a83a2448b9055c829a.mp4',
        'coverImage': 'assets/images/a45745c1d62743a83a2448b9055c829a.jpg',
        'author': '@生活Vlog',
        'avatarUrl': _getRandomAvatar(),
        'title': '记录日常点滴',
        'likeCount': _getRandomCount(),
        'commentCount': _getRandomCount(max: 5000),
        'shareCount': _getRandomCount(max: 2000),
      },
    ];
    
    // 转换为VideoItem对象
    videoList.value = videoData.map((data) => VideoItem.fromJson(data)).toList();
  }
  
  // 生成随机数量
  int _getRandomCount({int max = 10000}) {
    return Random().nextInt(max) + 100;
  }

  // 页面切换回调
  void onPageChanged(int index) {
    currentPageIndex.value = index;
    currentPlayingIndex.value = index;
  }

  // 点击视频切换播放状态
  void onVideoTap(int index) {
    // 由子组件处理播放暂停逻辑
  }
  
  // 点赞
  void onLikeTap(int index) {
    if (index < videoList.length) {
      final video = videoList[index];
      final currentLikes = video.likeCount ?? 0;
      // 更新点赞数（这里简单加1，实际应该调用API）
      videoList[index] = VideoItem(
        id: video.id,
        videoUrl: video.videoUrl,
        coverImage: video.coverImage,
        title: video.title,
        author: video.author,
        avatarUrl: video.avatarUrl,
        likeCount: currentLikes + 1,
        commentCount: video.commentCount,
        shareCount: video.shareCount,
      );
      videoList.refresh();
      LoadingUtil.toast('点赞成功');
    }
  }
  
  // 评论
  void onCommentTap(int index) {
    LoadingUtil.toast('评论功能开发中');
  }
  
  // 分享
  void onShareTap(int index) {
    LoadingUtil.toast('分享功能开发中');
  }

  // 更多按钮点击事件
  void onMoreTap() {
    // TODO: 实现更多功能
    LoadingUtil.toast('更多功能待开发');
  }

  // 搜索按钮点击事件
  void onSearchTap() {
    // TODO: 实现搜索功能
    LoadingUtil.toast('搜索功能待开发');
  }

  // 顶部Tab切换
  void onTopTabTap(int index) {
    currentTopTabIndex.value = index;
    
    // 切换到其他Tab时暂停视频
    if (index != 0) {
      debugPrint('$tag: 切换到其他Tab，暂停视频');
      _pauseVideo();
    } else {
      debugPrint('$tag: 切换回推荐Tab，恢复视频');
      _resumeVideo();
    }
    
    // 根据不同的tab显示不同提示
    final tabNames = ['推荐', '热播', '关注', '商城'];
    if (index < tabNames.length) {
      debugPrint('$tag: 切换到${tabNames[index]}');
    }
  }

  // ==================== 生命周期管理方法 ====================
  
  /// 初始化生命周期管理
  void _initLifecycleManagement() {
    try {
      debugPrint('$tag: 初始化生命周期管理');
      
      // 获取生命周期管理器
      _lifecycleManager = Get.find<AppLifecycleManager>();
      
      // 注册应用前台/后台回调
      _lifecycleManager?.addForegroundCallback(_onAppForeground);
      _lifecycleManager?.addBackgroundCallback(_onAppBackground);
      
      // 监听路由变化
      _setupRouteObserver();
      
      debugPrint('$tag: ✅ 生命周期管理初始化完成');
    } catch (e) {
      debugPrint('$tag: ❌ 生命周期管理器未找到: $e');
    }
  }
  
  /// 设置路由观察者
  void _setupRouteObserver() {
    if (_isRouteObserverRegistered) return;
    
    // 使用定时器轮询路由变化
    String? lastRoute = Get.currentRoute;
    
    _routeObserverTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!_isRouteObserverRegistered) {
        timer.cancel();
        return;
      }
      
      final currentRoute = Get.currentRoute;
      if (currentRoute != lastRoute) {
        debugPrint('$tag: 路由变化: $lastRoute → $currentRoute');
        _handleRouteChange(currentRoute);
        lastRoute = currentRoute;
      }
    });
    
    _isRouteObserverRegistered = true;
    debugPrint('$tag: ✅ 路由观察者已注册');
  }
  
  /// 处理路由变化
  void _handleRouteChange(String? route) {
    if (route == null) return;
    
    // 判断当前是否在首页
    final isOnHomePage = route.contains('home_index') || route == '/system_main';
    
    if (isOnHomePage && currentTopTabIndex.value == 0) {
      // 在首页且是推荐Tab
      debugPrint('$tag: 📱 返回首页，恢复视频播放');
      isPageVisible.value = true;
      _resumeVideo();
    } else {
      // 离开首页或切换到其他Tab
      debugPrint('$tag: 📱 离开首页，暂停视频播放');
      isPageVisible.value = false;
      _pauseVideo();
    }
  }
  
  /// 应用回到前台
  void _onAppForeground() {
    debugPrint('$tag: 🌞 应用回到前台');
    
    // 只有在首页且是推荐Tab时才恢复播放
    if (isPageVisible.value && currentTopTabIndex.value == 0) {
      if (_wasPlayingBeforeBackground) {
        debugPrint('$tag: ▶️ 恢复视频播放');
        _resumeVideo();
      }
    }
  }
  
  /// 应用进入后台
  void _onAppBackground() {
    debugPrint('$tag: 🌙 应用进入后台');
    
    // 记录当前播放状态
    _wasPlayingBeforeBackground = isVideoPlaying.value;
    
    // 暂停视频
    debugPrint('$tag: ⏸️ 暂停视频播放');
    _pauseVideo();
  }
  
  /// 暂停视频
  void _pauseVideo() {
    if (!isVideoPlaying.value) return;
    
    isVideoPlaying.value = false;
    debugPrint('$tag: ⏸️ 视频已暂停');
  }
  
  /// 恢复视频播放
  void _resumeVideo() {
    if (isVideoPlaying.value) return;
    
    isVideoPlaying.value = true;
    debugPrint('$tag: ▶️ 视频已恢复播放');
  }
  
  /// 清理生命周期管理
  void _cleanupLifecycleManagement() {
    try {
      debugPrint('$tag: 清理生命周期管理');
      
      // 取消路由观察器定时器
      _routeObserverTimer?.cancel();
      _routeObserverTimer = null;
      _isRouteObserverRegistered = false;
      
      // 移除回调
      _lifecycleManager?.removeForegroundCallback(_onAppForeground);
      _lifecycleManager?.removeBackgroundCallback(_onAppBackground);
      
      debugPrint('$tag: ✅ 生命周期管理已清理');
    } catch (e) {
      debugPrint('$tag: ❌ 清理生命周期管理失败: $e');
    }
  }

  @override
  void onInit() {
    super.onInit();
    debugPrint('$tag: onInit - 控制器初始化');
    _initData();
    _initLifecycleManagement();
  }

  @override
  void onReady() {
    super.onReady();
    debugPrint('$tag: onReady - 页面准备就绪');
    // 确保初始状态为播放
    isVideoPlaying.value = true;
    isPageVisible.value = true;
  }

  @override
  void onClose() {
    debugPrint('$tag: onClose - 控制器销毁');
    _cleanupLifecycleManagement();
    _pageController?.dispose();
    super.onClose();
  }
}
